# -*- coding:utf-8 -*-
from read_config import ReadConfig
import pymysql.cursors


class MysqlHander:
    def __init__(self, file):
        self.data = ReadConfig("database", file)
    
    def conn_mysql(self):
        #"""连接数据库"""
        host = self.data.get_db("host")
        user = self.data.get_db("user")
        password = self.data.get_db("password")
        db = self.data.get_db("db")
        charset = self.data.get_db("charset")
        self.conn = pymysql.connect(host=host, user=user, password=password, db=db, charset=charset)
        self.cur = self.conn.cursor()

    def execute_sql(self, sql, param):
        #"""执行操作数据的相关sql"""
        self.conn_mysql()
        self.cur.execute(sql, param)
        self.conn.commit()
        
    def execute_not_safe(self, sql):
        #"""执行操作数据的相关sql"""
        self.conn_mysql()
        self.cur.execute(sql)
        self.conn.commit()

    def query_sql(self, sql):
        #"""执行查询sql"""
        self.conn_mysql()
        self.cur.execute(sql)
        return self.cur.fetchall()

    def close_mysql(self):
        #"""关闭数据库连接"""
        self.cur.close()
        self.conn.close()
